import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //1、读取请求传来的参数
        req.setCharacterEncoding("utf8");
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        //2、验证用户名和密码
        if (!"张三".equals(username) || !"123".equals(password)){//输入数据是否为空都可正确判定（避免了空指针异常）
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前的用户或密码错误");
        }
        //3、登录成功，给此用户创建一个会话
        HttpSession session=req.getSession(true);
        session.setAttribute("username",username);
        session.setAttribute("loginTime",System.currentTimeMillis());
        //4、页面跳转到首页
        resp.sendRedirect("index");
    }
}

















